package com.csnf.dao.impl;

import com.csnf.dao.ICourseDao;
import com.csnf.entity.Course;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class CourseDaoImpl implements ICourseDao {
    public static SqlSession getSqlSession() throws IOException{
        String path = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(path);
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(resourceAsStream).openSession();
        return sqlSession;
    }

    @Override
    public List<Course> findAll() throws IOException {
        return getSqlSession().selectList("com.csnf.dao.ICourseDao.findAll");
    }

    @Override
    public List<Course> findByName(String name) throws IOException {
        return getSqlSession().selectList("com.csnf.dao.ICourseDao.findByName", name);
    }

    @Override
    public Integer save(Course course) throws IOException {
        SqlSession sqlSession = getSqlSession();
        Integer insert = sqlSession.insert("com.csnf.dao.ICourseDao.save", course);
        sqlSession.commit();
        sqlSession.close();
        return insert;
    }

    @Override
    public Integer deleteById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        Integer delete = sqlSession.delete("com.csnf.dao.ICourseDao.deleteById", id);
        sqlSession.commit();
        sqlSession.close();
        return delete;
    }
}
